package com.sgcc.pda.mdrh.h5.router;

import com.google.gson.Gson;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.hzaidl.entity.CommonErrorBean;
import com.sgcc.pda.hzaidl.entity.RequestBean;
import com.sgcc.pda.hzaidl.entity.ResponseBean;
import com.sgcc.pda.hzaidl.error.HZErrorCode;
import com.sgcc.pda.mdrh.h5.library.BridgeHandler;
import com.sgcc.pda.mdrh.h5.library.CallBackFunction;


public abstract class H5BridgeHandler implements BridgeHandler {

    private static final String TAG = "H5BridgeHandler";

    @Override
    public void handler(String data, CallBackFunction function) {
        LogUtil.e("收到H5请求: " + data);
        try {
            RequestBean requestBean = new Gson().fromJson(data, RequestBean.class);
            mixHandler(data,requestBean, function);
        } catch (Exception e) {
            e.printStackTrace();
            function.onCallBack(fail(HZErrorCode.ERROR_1000, "入参解析失败", null));
            return;
        }
    }

    public abstract void mixHandler(String data, RequestBean requestBean, CallBackFunction function);

    /**
     * 生成返回数据ResponseBean
     *
     * @param retCode 返回码
     * @param msgJson 返回数据json格式
     * @param tag     请求标识
     */
    private ResponseBean createResponseBean(int retCode, String msgJson, String tag) {
        ResponseBean responseBean = new ResponseBean();
        responseBean.setRetCode(retCode);
        responseBean.setMsgJson(msgJson);
        responseBean.setTag(tag);
        return responseBean;
    }

    /**
     * 错误返回
     *
     * @param errorCode 错误码
     * @param detailMsg 追加信息
     * @param tag       请求标识
     */
    private String fail(HZErrorCode errorCode, String detailMsg, String tag) {
        CommonErrorBean commonErrorBean = new CommonErrorBean(errorCode.getCode(), errorCode.getErrMessage() + "，" + detailMsg);
        ResponseBean responseBean = createResponseBean(0, new Gson().toJson(commonErrorBean), tag);
        return new Gson().toJson(responseBean);
    }
}
